﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using fuzhu;
using System.Data.SqlClient;

namespace GLY_XieTong
{
   public class GenVoucherNum
    {
       //单据号码
       public string cCardnum{get;set;}
       //连接字符串
       public string cConstr{get;set;}
       //单据ID，用于获取单据日期
       public int iId{get;set;}
       public GenVoucherNum(string ccardnum, int iid, string cconstr)
        {
            cCardnum= ccardnum;
            cConstr=cconstr;
            iId=iid;

        
        }
       /// <summary>
       /// 获得分段的号码
       /// </summary>
       /// <param name="VARCHAR"></param>
       /// <returns></returns>
       public string GetSecNum(string Prefix, int PrefixLen, string PrefixRule,SqlTransaction tran)
        {
            try
            {
                //返回值
                string cCode = "0";
                //取单据的前缀信息
                DateTime dDate;
                string cValue;
                string cTable, cFieldName, cIdName, cArchname;
                //获得当前段 对应的字段名称和参照档案
                string sql = string.Format("Select  cFieldName, cArchName from VoucherPrefabricateview Where CardNumber='{0}' AND cContent = '{1}'",
            cCardnum, Prefix);
                DataTable dt1 = DbHelper2.ExecuteTable(sql, cConstr);
                if (dt1.Rows.Count > 0)
                {
                    cFieldName = DbHelper.GetDbString(dt1.Rows[0]["cFieldName"]);
                    cArchname = DbHelper.GetDbString(dt1.Rows[0]["cArchName"]);
                }
                else
                {
                    throw new Exception("没有定义编码规则！");
                }
                //获取目标表的表名和主键
                sql = string.Format("SELECT BTTblName,VchTblPrimarykeyNames FROM vouchers WHERE CardNumber='{0}'", cCardnum);
                DataTable dt2 = DbHelper2.ExecuteTable(sql, cConstr);
                if (dt2.Rows.Count > 0)
                {
                    cTable = DbHelper.GetDbString(dt2.Rows[0]["BTTblName"]);
                    cIdName = DbHelper.GetDbString(dt2.Rows[0]["VchTblPrimarykeyNames"]);
                }
                else
                {
                    throw new Exception("无此单据号码！");
                }
                //    ---远程号或者手工输入，取0 或者 手工输入内容
                if (Prefix == "手工输入")
                {
                    cCode = "000000000" + @PrefixRule;
                    //cCode= cCode.Substring(cCode.Length-PrefixLen);
                }
                else if (Prefix == "远程号")
                {
                    cCode = "000000000";
                    //cCode= cCode.Substring(cCode.Length-PrefixLen);
                }
                else if (Prefix == "会计月份")
                {
                    sql = string.Format(@" select {0} from {1} where {2}='{3}'", cFieldName, cTable, cIdName, iId);
                    DateTime dVouDate = DbHelper.GetDbDate(DbHelper2.GetSingleWithTrans(sql, tran));
                    sql = string.Format(@"SELECT  iId FROM ufsystem..ua_period WHERE cAcc_id=dbo.fn_fd_getAccId() AND dbegin<='{0}' AND dend>='{0}'", dVouDate);
                    cCode = "000000000" + DbHelper.GetDbString(DbHelper2.GetSingleWithTrans(sql, tran));
                    //cCode= cCode.Substring(cCode.Length-PrefixLen);
                }
                else if (Prefix.Contains("日期"))
                {
                    //包含日期的
                    sql = string.Format(@"select  convert(varchar(20),{0},112) from {1} where {2}='{3}'", cFieldName, cTable, cIdName, iId);
                    cValue = DbHelper.GetDbString(DbHelper2.GetSingleWithTrans(sql, tran));
                    if (PrefixRule == "年月日")
                    {
                        cCode = "00" + cValue;
                        //cCode= cCode.Substring(cCode.Length-PrefixLen);
                    }
                    else if (PrefixRule == "年月")
                    {
                        cCode = "00" + cValue.Substring(0, 6);
                    }
                    else if (PrefixRule == "年")
                    {
                        cCode = "00" + cValue.Substring(0, 4);

                    }
                }
                else if (cArchname == "UA_User")
                {
                    //操作员,制单人
                    sql = string.Format(@"select  a.cUser_Id  from ufsystem..ua_user a,{0} b where a.cUser_Name=b.cmaker and b.{1}='{2}'", cTable, cIdName, iId);
                    cValue = DbHelper.GetDbString(DbHelper2.GetSingleWithTrans(sql, tran));
                    sql = string.Format(@"select ccode from Vouchercontrapose b where b.ccontent='UA_User' and b.cseed='{0}'", cValue);
                    cValue = DbHelper.GetDbString(DbHelper2.GetSingleWithTrans(sql, tran));
                    cCode = "0000" + cValue;
                }
                else
                {
                    sql = string.Format(@"select  ccode from  {0} a,Vouchercontrapose b where b.cseed=a.{1} and {2}='{3}' and b.ccontent='{4}'",
                        cTable, cFieldName, cIdName, iId, cArchname);
                    cValue = DbHelper.GetDbString(DbHelper2.GetSingleWithTrans(sql, tran));
                    cCode = "0000" + cValue;
                }


                cCode = cCode.Substring(cCode.Length - PrefixLen);
                return cCode;

            }
            catch (Exception ex)
            {
                WriteLog wr = new WriteLog();
                wr.WriteLogs(cCardnum + "获取单据号码错误：" + ex.Message);

                return "0";
            }
        }


       public string GetNum(SqlTransaction tran)
        {
        string cCode ="0";          
        //根据单据信息,取单据号
        //备注，如果用到日期外的其他前缀，勾上按对照码生成流水号
        string  Prefix1 ,Prefix2,Prefix3,Glide;
        int Prefix1Len ,Prefix2Len,Prefix3Len,GlideLen;
        string Prefix1Rule,Prefix2Rule,Prefix3Rule,GlideRule,bGlideByContraCode ;
        //string cseed; //流水种子，如果是 单据日期，只取4位数字
        string sql = string.Format(@"SELECT  Prefix1,Prefix1Len,Prefix1Rule,Prefix2,Prefix2Len,Prefix2Rule,
Prefix3,Prefix3Len,Prefix3Rule,Glide,GlideLen,GlideRule,bGlideByContraCode
  FROM  [VoucherNumber] WHERE CardNumber='{0}'",cCardnum);
       DataTable dt1 = DbHelper2.ExecuteTable(sql,cConstr);   
       if (dt1.Rows.Count>0)
       {
       Prefix1 = DbHelper.GetDbString(dt1.Rows[0]["Prefix1"]);
       Prefix1Len= DbHelper.GetDbInt(dt1.Rows[0]["Prefix1Len"]);
           Prefix1Rule = DbHelper.GetDbString(dt1.Rows[0]["Prefix1Rule"]);
           Prefix2 = DbHelper.GetDbString(dt1.Rows[0]["Prefix2"]);
           Prefix2Len = DbHelper.GetDbInt(dt1.Rows[0]["Prefix2Len"]);
           Prefix2Rule = DbHelper.GetDbString(dt1.Rows[0]["Prefix2Rule"]);
           Prefix3 = DbHelper.GetDbString(dt1.Rows[0]["Prefix3"]);
           Prefix3Len = DbHelper.GetDbInt(dt1.Rows[0]["Prefix3Len"]);
           Prefix3Rule = DbHelper.GetDbString(dt1.Rows[0]["Prefix3Rule"]);
           Glide = DbHelper.GetDbString(dt1.Rows[0]["Glide"]);         //流水依据
            GlideLen = DbHelper.GetDbInt(dt1.Rows[0]["GlideLen"]);     //
            GlideRule = DbHelper.GetDbString(dt1.Rows[0]["GlideRule"]);   // 流水规则
            bGlideByContraCode = DbHelper.GetDbString(dt1.Rows[0]["bGlideByContraCode"]);
       }
       else
       {
            throw new Exception("没有定义单据规则");
           return cCode;
       }



             string  c1="",c2="",c3="";//分段单据号
             string cqianzhui = "";  //流水前缀,流水种子，如果是 单据日期，取6位数字,如果是日期，取4位
             
            //先取前缀
            if (!string.IsNullOrEmpty(Prefix1) && Prefix1!="")
            {

                  c1= GetSecNum(Prefix1,Prefix1Len,Prefix1Rule,tran);
                  if (!string.IsNullOrEmpty(Glide) && Glide != "")
                  {
                      if (Glide.Contains(Prefix1))
                      {
                          if (Prefix1 == "单据日期")
                          {
                              if ((GlideRule == "年" && Prefix1Len == 2) || (GlideRule == "月" && Prefix1Len == 4) || (GlideRule == "日" && Prefix1Len == 6))
                              {
                                  cqianzhui = "20" + c1;
                              }
                              else if (GlideRule == "年" && Prefix1Len >4)
                              { 
                                  cqianzhui = c1.Substring(0,4);
                              }
                              else if (GlideRule == "月" && Prefix1Len > 6)
                              {
                                  cqianzhui = c1.Substring(0, 6);
                              }
                              else
                              {
                                  cqianzhui = c1;
                              }
                           
                          }
                          else
                          {
                              cqianzhui = c1;
                          }

                      }
                  }
            }
            if (!string.IsNullOrEmpty(Prefix2) && Prefix2!="")
            {

                c2 = GetSecNum(Prefix2, Prefix2Len, Prefix2Rule, tran);
                if (!string.IsNullOrEmpty(Glide) && Glide != "")
                {
                    if (Glide.Contains(Prefix2))
                    {

                        if (Prefix2 == "单据日期")
                        {
                            if ((GlideRule == "年" && Prefix1Len == 2) || (GlideRule == "月" && Prefix1Len == 4) || (GlideRule == "日" && Prefix1Len == 6))
                            {
                                cqianzhui += "20" + c2;
                            }
                            else if (GlideRule == "年" && Prefix1Len > 4)
                            {
                                cqianzhui += c2.Substring(0, 4);
                            }
                            else if (GlideRule == "月" && Prefix1Len > 6)
                            {
                                cqianzhui += c2.Substring(0, 6);
                            }
                            else
                            {
                                cqianzhui += c2;
                            }
                        }
                        else
                        {
                            cqianzhui += c2;
                        }

                    }
                }
            }
           if (!string.IsNullOrEmpty(Prefix3) && Prefix3!="")
            {

                c3 = GetSecNum(Prefix3, Prefix3Len, Prefix3Rule, tran);
                if (!string.IsNullOrEmpty(Glide) && Glide != "")
                {
                    if (Prefix3.Contains(Glide))
                    {
                        if (Prefix3 == "单据日期")
                        {
                            if ((GlideRule == "年" && Prefix1Len == 2) || (GlideRule == "月" && Prefix1Len == 4) || (GlideRule == "日" && Prefix1Len == 6))
                            {
                                cqianzhui += "20" + c3;
                            }
                            else if (GlideRule == "年" && Prefix1Len > 4)
                            {
                                cqianzhui += c3.Substring(0, 4);
                            }
                            else if (GlideRule == "月" && Prefix1Len > 6)
                            {
                                cqianzhui += c3.Substring(0, 6);
                            }
                            else
                            {
                                cqianzhui += c3;
                            }
                        }
                        else
                        {
                            cqianzhui += c3;
                        }
                    }
                }
            }
        cCode=c1+c2+c3;

  

//取最大值，voucherhistory
             int iMAX =1;
      sql = string.Format(@"SELECT count(1) sl FROM VoucherHistory WHERE cardnumber = '{0}' AND    ISNULL(cseed,'') =ISNULL('{1}','') AND ISNULL(ccontent,'')=ISNULL('{2}','')   AND ISNULL(ccontentrule,'')  = ISNULL('{3}','')",
          cCardnum,cqianzhui,Glide,GlideRule);
      int iCnt = DbHelper.GetDbInt(DbHelper2.GetSingleWithTrans(sql, tran));
       if (iCnt>0)
       {
          sql = string.Format(@"SELECT  cnumber FROM VoucherHistory WHERE cardnumber ='{0}' AND ISNULL(cseed,'') =ISNULL('{1}','') AND ISNULL(ccontent,'')=ISNULL('{2}','')   AND ISNULL(ccontentrule,'')  = ISNULL('{3}','')",
              cCardnum,cqianzhui,Glide,GlideRule);
         iMAX = DbHelper.GetDbInt(DbHelper2.GetSingleWithTrans(sql,tran));
         iMAX++;
           sql = string.Format(@"UPDATE VoucherHistory SET cnumber ={4}  WHERE cardnumber ='{0}' AND ISNULL(cseed,'') =ISNULL('{1}','') AND ISNULL(ccontent,'')=ISNULL('{2}','')   AND ISNULL(ccontentrule,'')  = ISNULL('{3}','')",
              cCardnum,cqianzhui,Glide,GlideRule,iMAX);
        DbHelper2.ExecuteSqlWithTrans(sql,tran);
        
      
       }          
   else
       {
           sql = string.Format(@"INSERT INTO  VoucherHistory(CardNumber,cContent,cContentRule,cSeed,cNumber,bEmpty) values('{0}','{1}','{2}','{3}',1,0)",
              cCardnum,Glide,GlideRule,cqianzhui);
       DbHelper2.ExecuteSqlWithTrans(sql,tran);
       }
      
       string cLiushui ="000000000000000"+ iMAX.ToString();
cCode=cCode+  cLiushui.Substring(cLiushui.Length-GlideLen);
  
        return cCode;
        }
    }
}
